<?php

namespace app\tool;

use app\model\Friends;
use app\model\User;
use think\facade\Cache;

class Msg
{
    public static function doType($dataArr, $ws, $fd, $ip)
    {
        switch ($dataArr['type']) {
            //登录
            case 'login':
                self::doLogin($dataArr, $ws, $fd, $ip);
                break;
            //发送消息
            case 'msg':
                self::doMsg($dataArr, $ws, $fd, $ip);
                break;
            //获取消息
            case 'getMsg':
                self::doGetMsg($dataArr, $ws, $fd, $ip);
                break;
            //获取用户列表
            case 'getUsers':
                self::doGetUsers($dataArr, $ws, $fd, $ip);
                break;
            //添加好友
            case 'addfriend':
                self::doAddfriend($dataArr, $ws, $fd, $ip);
                break;
            //websocket连接
            case 'wsconnect':
                self::doWsconnect($dataArr, $ws, $fd, $ip);
                break;
            //ping心跳
            case 'ping':
                self::doPing($dataArr, $ws, $fd, $ip);
                break;
        }
    }

    /**
     * 处理登录
     * $dataArr 前端参数
     * $ws websocket对象
     * $fd
     * $ip 客户端ip
     * @return void
     */
    public static function doLogin($dataArr, $ws, $fd, $ip)
    {
        $mongo     = new Mongo("8.130.18.175", 27017, 'jhx');
        $userQuery = [
            ['key' => 'username', 'value' => (string)$dataArr['username']],
            ['key' => 'password', 'value' => (string)$dataArr['password']],
        ];
        $users     = $mongo->query('user', $userQuery);
        if ($users) {
            $user       = $users[0];
            $updateUser = [
                ['key' => 'fd', 'value' => $fd]
            ];
            $mongo->update('user', $userQuery, $updateUser);
            Cache::set('user_' . $user->id, $user);
            $ws->to($fd)->emit('loginCallback', json_encode(['fd' => $fd, 'code' => 1, 'uid' => $user->id, 'msg' => 'success']));
        } else {
            $ws->emit('loginCallback', json_encode(['fd' => $fd, 'code' => -1, 'msg' => '登录失败']));
        }
    }


    //处理msg信息
    public static function doMsg($dataArr, $ws, $fd, $ip)
    {
        $uid  = (int)$dataArr['uid'];
        $fuid = (int)$dataArr['fuid'];
        $user = Cache::get('user_' . $uid);

        $mongo      = new Mongo("8.130.18.175", 27017, 'jhx');
        $fuserQuery = [
            ['key' => 'id', 'value' => $fuid]
        ];
        $fusers     = $mongo->query('user', $fuserQuery);
        $fuser      = $fusers[0];

        $ws->to([$fd, $fuser->fd])->emit('msgCallback', json_encode([
            'fd'       => $fd,
            'uid'      => $uid,
            'fuid'     => $dataArr['fuid'],
            'username' => $user->username,
            'ctime'    => time(),
            'msg'      => $dataArr['msg']
        ]));

        //数据写入mongodb
        $mongo = new Mongo("8.130.18.175", 27017, 'jhx');


        $addData = [
            ['uid' => $uid, 'fuid' => $fuid, 'username' => $user->username, 'msg' => $dataArr['msg'], 'ctime' => time(), 'relationid' => $uid . '_' . $fuid, 'is_read' => 1],
            ['uid' => $fuid, 'fuid' => $uid, 'username' => $user->username, 'msg' => $dataArr['msg'], 'ctime' => time(), 'relationid' => $fuid . '_' . $uid, 'is_read' => 0]
        ];
        $mongo->insert('message', $addData);
    }

    /**
     * 获取会员列表
     * @param $dataArr
     * @param $ws
     * @param $fd
     * @param $ip
     * @return void
     */
    public static function doGetUsers($dataArr, $ws, $fd, $ip)
    {
        $mongo       = new Mongo("8.130.18.175", 27017, 'jhx');
        $uid         = (int)$dataArr['uid'];
        $userQuery   = [
            ['key' => 'id', 'filter' => '$ne', 'value' => $uid],
        ];
        $friendQuery = [
            ['key' => 'uid', 'value' => $uid],
        ];
        $users       = $mongo->query('user', $userQuery);
        $friends     = $mongo->query('friends', $friendQuery);

        $fuids = [];
        foreach ($friends as $friend) {
            $fuids[] = (int)$friend->fuid;
        }

        $userData = [];
        foreach ($users as $v) {
            $isFriend = 0;
            if (in_array($v->id, $fuids)) {
                $isFriend = 1;
            }
            $userData[] = [
                'id'       => (int)$v->id,
                'username' => $v->username,
                'isfriend' => (int)$isFriend
            ];
        }
        $ws->to($fd)->emit('getUsersCallback', json_encode([
            'fd'       => $fd,
            'userData' => json_encode($userData)
        ]));
    }

    public static function doAddfriend($dataArr, $ws, $fd, $ip)
    {
        $mongo        = new Mongo("8.130.18.175", 27017, 'jhx');
        $uid          = (int)$dataArr['uid'];
        $fuid         = (int)$dataArr['fuid'];
        $friendsQuery = [
            ['key' => 'uid', 'value' => $uid],
            ['key' => 'fuid', 'value' => $fuid],
        ];
        $has          = $mongo->query('user', $friendsQuery);

        if ($has) {
            $ws->to($fd)->emit('addfriendCallback', json_encode([
                'code' => 0,
                'fd'   => $fd,
                'msg'  => '已经是好友'
            ]));
        } else {
            $addArr = [
                ['uid' => $uid, 'fuid' => $fuid, 'create_time' => time()],
                ['uid' => $fuid, 'fuid' => $uid, 'create_time' => time()],
            ];
            $mongo->insert('friends', $addArr);

            $ws->to($fd)->emit('addfriendCallback', json_encode([
                'code' => 1,
                'fd'   => $fd,
                'msg'  => '添加成功'
            ]));
        }
    }

    public static function doWsconnect($dataArr, $ws, $fd, $ip)
    {
        $mongo     = new Mongo("8.130.18.175", 27017, 'jhx');
        $uid       = (int)$dataArr['uid'];
        $userQuery = [
            ['key' => 'id', 'value' => $uid],
        ];
        $users     = $mongo->query('user', $userQuery);

        if ($users && $users[0]->fd != $fd) {
            $updateArr = [
                ['key' => 'fd', 'value' => $fd]
            ];
            $mongo->update('user', $userQuery, $updateArr);
        }
    }

    public static function doPing($dataArr, $ws, $fd, $ip)
    {
        $ws->to($fd)->emit('pong', json_encode([
            'code' => 0,
            'fd'   => $fd,
            'msg'  => 'pong'
        ]));
    }

    public static function doGetMsg($dataArr, $ws, $fd, $ip)
    {
        $mongo        = new Mongo("8.130.18.175", 27017, 'jhx');
        $uid          = (int)$dataArr['uid'];
        $fuid         = (int)$dataArr['fuid'];
        $messageQuery = [
            ['key' => 'uid', 'value' => $uid],
            ['key' => 'fuid', 'value' => $fuid],
        ];
        $updateData = [
            ['key'=>'is_read','value'=>1]
        ];
        $messages     = $mongo->query('message', $messageQuery);
        $mongo->update('message', $messageQuery,$updateData);

        $ws->to($fd)->emit('getMsgCallback', json_encode([
            'code' => 1,
            'fd'   => $fd,
            'msg'  => '添加成功',
            'message'=>json_encode($messages)
        ]));
    }
}